<template>

  <a-modal
    title="岗位多选框"
    :width="750"
    :visible="visible"
    :closable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <div ref="box">
      <a-transfer
        :data-source="allPositions"
        :target-keys="targetKeys"
        :show-search="showSearch"
        :filter-option="(inputValue, item) => (item.name.indexOf(inputValue) !== -1||item.code.indexOf(inputValue) !== -1)"
        :show-select-all="true"
        @change="onChange"
      >
        <template
          slot="children"
          slot-scope="{
            props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
            on: { itemSelectAll, itemSelect },
          }"
        >
          <div class="selectWrap">
            <j-dict-select-tag
              placeholder="请选择岗位类别"
              type="list"
              @input="positionCategoryChange"
              style="width: 100%"
              v-model="selectedPositionCategory"
              dictCode="position_category"/>
          </div>
          <div>
            <a-table
              :row-selection="
                getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
              "
              :columns="direction === 'left' ? leftColumns : rightColumns"
              :data-source="filteredItems"
              size="small"
              :style="{ pointerEvents: listDisabled ? 'none' : null }"
              :custom-row="
                ({ key, disabled: itemDisabled }) => ({
                  on: {
                    click: () => {
                      if (itemDisabled || listDisabled) return;
                      itemSelect(key, !selectedKeys.includes(key));
                    },
                  },
                })
              "
            />
          </div>

        </template>
      </a-transfer>
    </div>
  </a-modal>
</template>
<script>
import difference from 'lodash/difference';
import {getAction} from '@api/manage';

const leftTableColumns = [
  {
    dataIndex: 'name',
    title: '岗位名称'
  },
  {
    dataIndex: 'code',
    title: '岗位编码'
  }
];
const rightTableColumns = [
    {
      dataIndex: 'name',
      title: '岗位名称'
    },
    {
      dataIndex: 'code',
      title: '岗位编码'
    }
  ];

  export default {
    name: 'PositionMultiSelectModal',
    props: {
      currentPositions: Array
    },
    data() {
      return {
        // mockData,
        targetKeys: [],
        disabled: false,
        showSearch: true,
        leftColumns: leftTableColumns,
        rightColumns: rightTableColumns,
        visible: false,
        selectedPosition: [],
        selectedPositionCategory: '',
        url: {
          positionList: '/api/erpmng/sys/position/list'
        },
        allPositions: []
      };
    },
    mounted() {
      const temAllPositions = []
      const allPositions = []
      this.targetKeys = []
      getAction('/api/erpmng/sys/position/list', {}).then((res) => {
        console.log('res', res)
        if (res.success && res.result.records && res.result.records.length > 0) {
          res.result.records.forEach((item, index) => {
            let p = {}
            p.key = index.toString()
            p.id = item.id
            p.name = item.name
            p.code = item.code
            p.title = ''
            p.description = ''
            p.disabled = false
            allPositions.push(p);
            temAllPositions.push(p)
          })
        }
        temAllPositions.forEach((item, index) => {
          this.currentPositions.forEach((v1, i1) => {
            if (item.id === v1) {
              this.targetKeys.push(index.toString())
            }
          })
        })
        console.log("this.targetKeys", this.targetKeys)
        this.allPositions = allPositions
      })
    },
    watch: {
      'targetKeys': {
        handler(val, oldName) {
          console.log('val', val)
          this.selectedPosition = []
          if (val && val.length > 0) {
            val.forEach((item, index) => {
              let p = {}
              p.key = this.allPositions[item].key
              p.id = this.allPositions[item].id
              p.name = this.allPositions[item].name
              p.code = this.allPositions[item].code
              this.selectedPosition.push(p)
            })
            let arr = []
            val.forEach((item, index) => {
              if (!this.targetKeys.some(p => {
                if (p.id === item.id) {
                  return true;
                }
              })) {
                let p = {}
                p.key = index.toString()
                p.id = item.id
                p.name = item.name
                p.code = item.code
                arr.push(p);
              }
            })
            if (arr.length > 0) {
              this.allPositions = arr
            }
          }
        },
        deep: true,
        immediate: true
      }
    },
    methods: {
      initDictData() {
      },
      show(ids) {
        this.visible = true
        console.log('ids', ids)
        // if(ids&&ids.length>0) {
        //   this.currentPositions = ids
        // }
        this.$nextTick(() => {
          if (this.$refs.box.firstChild.lastChild.lastChild.lastChild.firstChild !== null) {
            this.$refs.box.firstChild.lastChild.lastChild.lastChild.firstChild.style.display = 'none'
            this.$refs.box.firstChild.lastChild.lastChild.firstChild.style.position = 'absolute'
            this.$refs.box.firstChild.lastChild.lastChild.firstChild.style.top = '0%'
          }
          if (this.$refs.box.firstChild.lastChild.lastChild.lastChild.firstChild.firstChild) {
            this.$refs.box.firstChild.lastChild.lastChild.lastChild.firstChild.firstChild.style.marginTop = '60px'
            this.$refs.box.firstChild.lastChild.lastChild.lastChild.firstChild.firstChild.firstChild.firstChild.firstChild.style.marginTop = '0'
          }
        })
      },
      handleCancel() {
        this.close()
      },
      handleOk() {
        console.log('this.selectedPosition', this.selectedPosition)
        this.$emit('selectFinish', this.selectedPosition);
        this.visible = false;
      },
      close() {
        this.$emit('close');
        this.visible = false;
      },
      positionCategoryChange(e) {
        getAction('/api/erpmng/sys/position/list', {'positionCategory': e}).then((res) => {
          if (res.success && res.result.records && res.result.records.length > 0) {
            res.result.records.forEach((item, index) => {
              if (!this.targetKeys.some(p => {
                if (p.id == item.id) {
                  return true;
                }
              })) {
                let p = {}
                p.key = index.toString()
                p.id = item.id
                p.name = item.name
                p.code = item.code
                this.allPositions.push(p);
              }
            })
          }
        })
      },
      onChange(nextTargetKeys) {
        // this.$set(this.targetKeys,0,nextTargetKeys);
        this.targetKeys = []
        nextTargetKeys.map((item, key) => {
          this.$set(this.targetKeys, key, item)
        })
      },
      getRowSelection({disabled, selectedKeys, itemSelectAll, itemSelect}) {
        return {
          getCheckboxProps: item => ({props: {disabled: disabled || item.disabled}}),
          onSelectAll(selected, selectedRows) {
            const treeSelectedKeys = selectedRows
              .filter(item => !item.disabled)
              .map(({key}) => key);
            const diffKeys = selected
              ? difference(treeSelectedKeys, selectedKeys)
              : difference(selectedKeys, treeSelectedKeys);
            itemSelectAll(diffKeys, selected);
          },
          onSelect({key}, selected) {
            itemSelect(key, selected);
          },
          selectedRowKeys: selectedKeys
        };
      }
    }
  };
</script>
<style lang="less" scoped>
  ::v-deep .ant-transfer-customize-list .ant-transfer-list-body-with-search {
    position: relative !important;
  }

  ::v-deep .ant-table-wrapper {
    margin-top: 100px;
  }

  ::v-deep .ant-transfer-customize-list .ant-transfer-list-body-search-wrapper {
    position: absolute !important;
    top: 10%;
  }

</style>
